import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import moment from 'moment'
import {
  Button,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  notification,
  Popconfirm,
  Select,
  Space,
  Table,
  Image,
  DatePicker,
} from 'antd'
import { useForm } from 'antd/lib/form/Form'
import React, { useEffect, useState } from 'react'
import { request } from '../../api/request'

interface CRUDPageProps {
  queryUrl?: String
  addUrl?: String
  deleteUrl?: String
  updateUrl?: String
  module?: String
  childColumns?: any[]
  operate?: 'order' | 'other'
}

const CRUDPage: React.FC<CRUDPageProps> = ({
  queryUrl,
  addUrl,
  deleteUrl,
  updateUrl,
  module = '',
  childColumns = [],
  operate = 'other',
}) => {
  const [dataSource, setDataSource] = useState([])
  const [columns, setColumns] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [recode, setRecode] = useState({})
  useEffect(() => {
    getData(1, 10)
  }, [])

  const getData = (
    page: number,
    pageSize: number | undefined,
    data: object = {}
  ) => {
    setLoading(true)
    request
      .get({
        url: `${queryUrl}?page=${page}&pageSize=${pageSize}`,
        data: data,
      })
      .then((data) => {
        let operate = {
          title: '操作',
          dataIndex: 'operate',
          fixed: 'right',
          width: 150,
          render: (text: string, recode: any) => {
            return (
              <Space size={2}>
                <Button
                  size='small'
                  type='primary'
                  onClick={() => {
                    setRecode(recode)
                    setIsModalVisible(true)
                  }}
                  icon={<EditOutlined />}
                />
                <Popconfirm
                  title='你确定要删除吗?'
                  onConfirm={() => {
                    request
                      .delete({ url: deleteUrl, data: [recode.id] })
                      .then((data: any) => {
                        message.success(data.message)
                        getData(1, 10)
                      })
                      .catch((e) => {})
                  }}
                  onCancel={() => {}}
                  okText='确认删除'
                  cancelText='取消'
                >
                  <Button
                    size='small'
                    type='primary'
                    icon={<DeleteOutlined />}
                    danger
                  />
                </Popconfirm>
              </Space>
            )
          },
        }
        let tmpColums = data.data.columns

        tmpColums.map((item: any, index: number) => {
          if (item.showKey !== null && item.showKey !== undefined) {
            tmpColums[index].render = (text: string, recode: any) => {
              return (
                <div key={index}>
                  {recode?.[item.showKey[0]]?.[item.showKey[1]]}
                </div>
              )
            }
          }
          if (item.dataType === 'image') {
            tmpColums[index].render = (text: string, recode: any) => {
              return (
                <Image.PreviewGroup key={index}>
                  <Image width={40} src={text} />
                </Image.PreviewGroup>
              )
            }
          }
        })

        childColumns.length > 0 && tmpColums.push(...childColumns)
        tmpColums.push(operate)
        setColumns(tmpColums)
        setDataSource(data.data.recode)
        setTotal(data.data.total)
        setLoading(false)
      })
      .catch((e) => {
        setLoading(false)
      })
  }

  return (
    <>
      <SearchForm columns={columns} getData={getData} />
      {operate === 'order' ? null : (
        <Space size={4} style={{ width: '100%' }}>
          <Button
            type='primary'
            onClick={() => {
              setIsModalVisible(true)
              setRecode(false)
            }}
          >
            添加{`${module}`}
          </Button>
        </Space>
      )}

      <DataTable
        dataSource={dataSource}
        columns={columns}
        total={total}
        getData={getData}
        loading={loading}
      />

      <DataModal
        isModalVisible={isModalVisible}
        setIsModalVisible={setIsModalVisible}
        recode={recode}
        columns={columns}
        getData={getData}
        addUrl={addUrl}
        updateUrl={updateUrl}
      />
    </>
  )
}

export default CRUDPage

interface SearchFormProps {
  columns?: any[]
  getData?: (
    page: number,
    pageSize: number | undefined,
    userName: String
  ) => void
}
// 搜索栏目
const SearchForm: React.FC<SearchFormProps> = ({ columns, getData }) => {
  const [form] = useForm()
  return (
    <Form
      form={form}
      onFinish={() => getData && getData(1, 10, form.getFieldsValue())}
    >
      <Space size={4}>
        {columns?.map((item, index) => {
          if (
            item.showType === undefined ||
            item.showType === null ||
            !item.showType[3]
          ) {
            return null
          }
          if (typeof item.dataType !== 'string') {
            return (
              <Form.Item key={index} name={item.key} label={item.title}>
                <Select
                  style={{ width: 180 }}
                  allowClear
                  placeholder={`请选择${item.title}`}
                >
                  {item.dataType.map((op: any, index: number) => {
                    return (
                      <Select.Option key={index} value={op.value}>
                        {op.title}
                      </Select.Option>
                    )
                  })}
                </Select>
              </Form.Item>
            )
          }

          return (
            <Form.Item key={index} name={item.key} label={item.title}>
              <Input placeholder={`请输入${item.title}`} />
            </Form.Item>
          )
        })}
        <Form.Item>
          <Button type='primary' htmlType='submit'>
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type='ghost' htmlType='reset'>
            重置
          </Button>
        </Form.Item>
      </Space>
    </Form>
  )
}

interface DataTableProps {
  dataSource?: any[]
  columns?: any[]
  total?: number
  loading?: boolean
  getData?: (page: number, pageSize: number | undefined) => void
}

// 数据表
const DataTable: React.FC<DataTableProps> = ({
  dataSource,
  columns,
  total,
  loading = false,
  getData,
}) => {
  return (
    <Table
      key='id'
      rowKey='id'
      dataSource={dataSource}
      columns={columns}
      size='small'
      loading={loading}
      style={{ width: '100%' }}
      pagination={{
        total: total,
        showQuickJumper: true,
        // hideOnSinglePage: true,
        responsive: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showSizeChanger: true,
        showTotal: (_total: number) => {
          return `总共 ${_total} 条`
        },
        onChange: (page: number, pageSize: number | undefined) => {
          getData && getData(page, pageSize)
        },
      }}
    />
  )
}

interface DataModalProps {
  setIsModalVisible: (isVisible: boolean) => void
  getData: (
    page: number,
    pageSize: number | undefined,
    userName?: String
  ) => void
  isModalVisible: boolean
  recode?: any
  columns?: any[]
  addUrl?: String
  updateUrl?: String
}

// 添加数据or修改数据
const DataModal: React.FC<DataModalProps> = ({
  isModalVisible,
  setIsModalVisible,
  getData,
  recode,
  columns,
  addUrl,
  updateUrl,
}) => {
  const [form] = useForm()

  const addData = () => {
    form.validateFields().then((res) => {
      request
        .post({
          url: addUrl,
          data: res,
        })
        .then((data: any) => {
          if (data.code !== 200) {
            message.warn(data.message)
            return
          }
          message.success(data.message)
          form.resetFields()
          setIsModalVisible(false)
          getData(1, 10)
        })
        .catch((e) => {
          notification['error']({
            message: '服务器启动中...',
            description: 'http请求出错了！',
          })
        })
    })
  }

  const updateData = () => {
    form.validateFields().then((res) => {
      request
        .put({
          url: updateUrl,
          data: res,
        })
        .then((data: any) => {
          if (data.code !== 200) {
            message.warn(data.message)
            return
          }
          message.success(data.message)
          form.resetFields()
          setIsModalVisible(false)
          getData(1, 10)
        })
        .catch((e) => {
          notification['error']({
            message: '服务器启动中...',
            description: 'http请求出错了！',
          })
        })
    })
  }

  const handleOk = () => {
    recode ? updateData() : addData()
  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }

  useEffect(() => {
    if (!!recode) {
      let tmp = recode
      tmp?.endTime
        ? (tmp['endTime'] = moment(
            new Date(tmp['endTime']),
            'YYYY-MM-DD HH:mm:ss'
          ))
        : (tmp['endTime'] = moment(new Date(), 'YYYY-MM-DD HH:mm:ss'))
      form.setFieldsValue({ ...tmp })
    } else {
      form.resetFields()
    }
  }, [recode])

  return (
    <>
      <Modal
        title={!!recode ? '修改' : '添加'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {recode && (
            <Form.Item name='id' label='ID'>
              <Input defaultValue={recode.id} disabled />
            </Form.Item>
          )}
          {columns?.map((item, index) => {
            if (
              item.dataIndex === 'operate' ||
              item.dataIndex === 'id' ||
              item.showType === undefined ||
              item.showType === null
            ) {
              return null
            }

            if (!!recode) {
              if (!item.showType[2]) {
                return null
              }
            } else {
              if (!item.showType[0]) {
                return null
              }
            }

            if (typeof item.dataType !== 'string') {
              return (
                <Form.Item
                  key={index}
                  name={item.key}
                  label={item.title}
                  rules={[{ required: true, message: `${item.title}不能为空` }]}
                >
                  <Select style={{ width: '100%' }} allowClear>
                    {item.dataType.map((op: any, index: number) => {
                      return (
                        <Select.Option
                          key={index}
                          value={op.value === null ? 0 : op.value}
                        >
                          {op.value === null ? 0 : op.title}
                        </Select.Option>
                      )
                    })}
                  </Select>
                </Form.Item>
              )
            }

            if (item.dataType === 'text') {
              return (
                <Form.Item
                  name={item.key}
                  label={item.title}
                  key={index}
                  rules={[{ required: true, message: `${item.title}不能为空` }]}
                >
                  <Input.TextArea
                    placeholder={`请输入${item.title}`}
                    maxLength={255}
                    showCount
                  />
                </Form.Item>
              )
            }

            if (item.dataType === 'number') {
              return (
                <Form.Item
                  name={item.key}
                  label={item.title}
                  key={index}
                  rules={[{ required: true, message: `${item.title}不能为空` }]}
                >
                  <InputNumber
                    style={{ width: '100%' }}
                    min={0}
                    placeholder={`请输入${item.title}`}
                  />
                </Form.Item>
              )
            }

            if (item.dataType === 'time') {
              console.log(item)

              return (
                <Form.Item
                  name={item.key}
                  label={item.title}
                  key={index}
                  rules={[{ required: true, message: `${item.title}不能为空` }]}
                >
                  <DatePicker
                    showTime
                    format='YYYY-MM-DD HH:mm:ss'
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              )
            }

            return (
              <Form.Item
                name={item.key}
                label={item.title}
                key={index}
                rules={[{ required: true, message: `${item.title}不能为空` }]}
              >
                <Input placeholder={`请输入${item.title}`} />
              </Form.Item>
            )
          })}
        </Form>
      </Modal>
    </>
  )
}
